package me.gacl.websocket;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 轮循任务管理器
 * 
 * @author xdp
 * 
 */
public class RotationTaskManager {

	/** 最大线程数 */
	private static final int MAX_THREAD_SIZE = 10;
	/** 单一实例 */
	private static RotationTaskManager sInstance;

	private ScheduledThreadPoolExecutor threadPoolExecutor;

	private List<ScheduledFuture<?>> futures = Collections.synchronizedList(new ArrayList<ScheduledFuture<?>>());

	private RotationTaskManager() {
		threadPoolExecutor = new ScheduledThreadPoolExecutor(MAX_THREAD_SIZE);
	}

	/**
	 * 获取单一实例
	 * 
	 * @return 单一实例
	 */
	public static RotationTaskManager getInstance() {
		if (sInstance == null) {
			synchronized (RotationTaskManager.class) {
				if (sInstance == null) {
					sInstance = new RotationTaskManager();
				}
			}
		}
		return sInstance;
	}

	/**
	 * 增加轮循任务并开始执行
	 * 
	 * @param task
	 *            重复执行的任务
	 * @param period
	 *            每个周期执行时间，单位秒
	 */
	public void addTaskAndRun(Runnable task, long period) {
		ScheduledFuture<?> future = threadPoolExecutor.scheduleWithFixedDelay(task, 0, period, TimeUnit.SECONDS);
		futures.add(future);
	}

	/**
	 * 添加一次性（不轮训）的任务并开始执行
	 * 
	 * @param task
	 *            执行的任务
	 * @param firstRunDelay
	 *            执行的延时时间，单位秒
	 */
	public void addOneshotTaskAndRun(Runnable task, long firstRunDelay) {
		ScheduledFuture<?> future = threadPoolExecutor.schedule(task, firstRunDelay, TimeUnit.SECONDS);
		futures.add(future);
	}

	/**
	 * 增加轮循任务并执行
	 * 
	 * @param task
	 *            重复执行的任务
	 * @param firstRunDelay
	 *            第一次执行的延时时间，单位秒
	 * @param period
	 *            每个周期执行时间，单位秒
	 */
	public void addTaskAndRun(Runnable task, long firstRunDelay, long period) {
		ScheduledFuture<?> future = threadPoolExecutor.scheduleWithFixedDelay(task, firstRunDelay, period,
				TimeUnit.SECONDS);
		futures.add(future);
	}

	/**
	 * 停止所有轮循任务
	 * 
	 * @param forceClose
	 *            true强制关闭正在执行的任务
	 */
	public void stopAllTask(boolean forceClose) {
		for (ScheduledFuture<?> future : futures) {
			if (future != null && !future.isCancelled()) {
				future.cancel(forceClose);
			}
		}
		threadPoolExecutor.purge();
	}

	/** 停止所有轮循任务并释放资源 */
	public void release() {
		stopAllTask(true);
		threadPoolExecutor.shutdown();
		futures.clear();
		sInstance = null;
	}
}
